import { ref, nextTick, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import XEUtils from 'xe-utils'
import Sortable from 'sortablejs'

export default function(data, sortFn = () => {}) {
  const showHelpTip = ref(false)
  const xGrid = ref(null)

  const sort = (nodes, parentId) => {
    const arr = nodes.map((item, index) => {
      return sortFn(item, index, parentId)
    })
  }

  let sortable

  // tree拖拽排序
  const treeDrop = () => {
    const $grid = xGrid.value
    sortable = Sortable.create($grid.$el.querySelector('.body--wrapper>.vxe-table--body tbody'), {
      handle: '.drag-btn',
      onEnd: (sortableEvent) => {
        const targetTrElem = sortableEvent.item
        const oldIndex = sortableEvent.oldIndex
        const options = { children: 'children' }
        const wrapperElem = targetTrElem.parentNode
        const prevTrElem = targetTrElem.previousElementSibling
        const tableTreeData = data.value
        const targetRowNode = $grid.getRowNode(targetTrElem)
        if (!targetRowNode) {
          return
        }
        const selfRow = targetRowNode.item
        const selfNode = XEUtils.findTree(tableTreeData, row => row === selfRow, options)
        if (prevTrElem) {
          console.log('移动到节点')
          // 移动到节点
          const prevRowNode = $grid.getRowNode(prevTrElem)
          if (!prevRowNode) {
            return
          }
          const prevRow = prevRowNode.item
          const prevNode = XEUtils.findTree(tableTreeData, row => row === prevRow, options)
          if (XEUtils.findTree(selfRow[options.children], row => prevRow === row, options)) {
            // 错误的移动
            const oldTrElem = wrapperElem.children[oldIndex]
            wrapperElem.insertBefore(targetTrElem, oldTrElem)
            return ElMessage.error('不允许拖动父节点到自身的子节点！')
          }
          const currRow = selfNode.items.splice(selfNode.index, 1)[0]
          if ($grid.isTreeExpandByRow(prevRow)) {
            // 移动到当前的子节点
            prevRow[options.children].splice(0, 0, currRow)
            console.log('移动到当前的子节点：item.children排序', prevNode)
            const parentId = prevNode.item.id
            sort(prevNode.item.children, parentId)
          } else {
            // 移动到相邻节点
            prevNode.items.splice(prevNode.index + (selfNode.index < prevNode.index ? 0 : 1), 0, currRow)
            console.log('移动到相邻节点：items内部进行排序', prevNode)
            const parentId = prevNode.parent ? prevNode.parent.id : '0'
            sort(prevNode.items, parentId)
          }
        } else {
          // 移动到第一行
          const currRow = selfNode.items.splice(selfNode.index, 1)[0]
          tableTreeData.unshift(currRow)
          console.log('移动到第一行:tableTreeData排序', tableTreeData)
          sort(tableTreeData, '0')
        }
        // 如果变动了树层级，需要刷新数据
        data.value = [...tableTreeData]
        
      }
    })
  }

  let initTime
  nextTick(() => {
    // 加载完成之后在绑定拖动事件
    initTime = setTimeout(() => {
      treeDrop()
    }, 500)
  })

  onUnmounted(() => {
    clearTimeout(initTime)
    if (sortable) {
      sortable.destroy()
    }
  })

  return {
    showHelpTip,
    xGrid,
    treeDrop
  }
}